<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1200px">
    <ContentWrap>
      <div style="display: flex">
        <div class="mr-6">
          <el-form :model="taskData" ref="formRef" label-width="auto" :rules="formRules">
            <el-form-item label="任务名称" prop="name">
              <el-input v-model="taskData.name" />
            </el-form-item>
            <el-form-item label="发件人" prop="senderId">
              <el-select
                v-model="taskData.senderId"
                class="mr-2"
                @change="handleSenderAddressChange"
              >
                <el-option
                  v-for="sender in senderData"
                  :key="sender.id"
                  :label="
                    sender.senderName +
                    '<' +
                    sender.senderAddress +
                    '@' +
                    sender.domain.domainName +
                    '>'
                  "
                  :value="sender.id"
                />
              </el-select>
              <el-button style="width: 12px" @click="handleSenderCreate">
                <Icon icon="ep:plus" style="margin-left: 4px" />
              </el-button>
            </el-form-item>
            <el-form-item label="回复地址" prop="replyId">
              <el-select v-model="taskData.replyId" class="mr-2">
                <el-option
                  v-for="reply in replyData"
                  :key="reply.id"
                  :label="reply.replyName + '<' + reply.replyAddress + '>'"
                  :value="reply.id"
                />
              </el-select>
              <el-button style="width: 12px" @click="handleReplyCreate">
                <Icon icon="ep:plus" style="margin-left: 4px" />
              </el-button>
            </el-form-item>
            <el-form-item label="邮件主题" prop="subject">
              <el-input
                v-model="taskData.subject"
                class="mr-2"
                type="textarea"
                style="width: 240px"
                ref="subjectInputRef"
              />
              <el-popover :visible="subjectMacroVisible" :width="150">
                <el-button
                  v-for="(item, index) in subjectMacro"
                  class="ml-3"
                  style="border: none"
                  :key="index"
                  @click="handleSubjectMacroClick(index)"
                >
                  {{ item }}
                </el-button>

                <template #reference>
                  <el-button @click="subjectMacroVisible = !subjectMacroVisible">
                    主题宏
                  </el-button>
                </template>
              </el-popover>
            </el-form-item>
            <el-form-item label="定时发送" prop="isScheduled">
              <el-switch v-model="taskData.isScheduled" />
            </el-form-item>
            <el-form-item label="发送时间" prop="sendTime" v-if="taskData.isScheduled">
              <el-date-picker
                v-model="taskData.sendTime"
                placeholder="请输入发送时间"
                :clearable="true"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-form>
          <div class="flex mb-2">
            <div>
              <span style="font-weight: bold; margin-right: 3px">接收对象:</span>
              <span>已选择{{ selectCount }}个邮箱地址</span>
            </div>
            <el-button
              link
              style="margin-left: auto"
              @click="isShowQueryCondition = !isShowQueryCondition"
            >
              <Icon :icon="isShowQueryCondition ? 'ep:arrow-down' : 'ep:arrow-right'" />
            </el-button>
          </div>
          <div v-show="isShowQueryCondition">
            <Table
              ref="tableRef"
              :columns="columns"
              :data="receiversData"
              :height="330"
              @select="handleTableSelectChange"
              @select-all="handleTableSelectChange"
            />
          </div>
        </div>
        <div style="flex: 1">
          <div style="display: flex">
            <el-text>营销模板：</el-text>
            <el-select
              v-model="templateId"
              style="width: 200px"
              class="mr-3"
              @change="handleTemplateChange"
            >
              <el-option
                v-for="template in templateList"
                :key="template.id"
                :label="template.name"
                :value="template.id"
              />
            </el-select>
            <UploadFile
              v-model="fileList"
              :show-file-list="false"
              :is-show-tip="false"
              :fileSize="32"
            >
              <el-button><Icon icon="mdi:paperclip" />附件</el-button>
            </UploadFile>
            <el-popover :width="150" :visible="signatureVisible">
              <el-button
                v-for="(item, index) in signatureList"
                class="ml-3"
                style="border: none; min-width: 120px"
                :key="index"
                @click="handleSignatureClick(index)"
              >
                {{ item.name }}
              </el-button>

              <template #reference>
                <el-button @click="signatureVisible = !signatureVisible">签名</el-button>
              </template>
            </el-popover>
            <el-popover :width="150" :visible="contentMacroVisible">
              <el-button
                v-for="(item, index) in contentMacro"
                class="ml-3"
                style="border: none; min-width: 120px"
                :key="index"
                @click="handleContentMacroClick(index)"
              >
                {{ item }}
              </el-button>

              <template #reference>
                <el-button @click="contentMacroVisible = !contentMacroVisible"> 正文宏 </el-button>
              </template>
            </el-popover>
          </div>
          <FileList v-model="fileList">
            <template #menu="{ item }">
              <context-menu-item label="删除" @click="handleDeleteResource(item)" />
              <context-menu-item label="重命名" @click="handleRenameResource(item)" />
              <context-menu-item label="复制附件名" @click="handleCopyResourceName(item)" />
            </template>
          </FileList>
          <Editor ref="editorRef" v-model="taskData.content.content" />
        </div>
      </div>
    </ContentWrap>
    <template #footer>
      <el-button @click="saveTask">保存为草稿</el-button>
      <el-button type="primary" @click="sendTask">
        <div v-if="!taskData.isScheduled">发送</div>
        <div v-else>定时发送</div>
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <ReplyEdit ref="replyEditRef" @success="replyEditSuccess" />
  <SenderEdit ref="senderEditRef" @success="senderEditSuccess" />
  <RenameFile ref="renameFileRef" @success="saveResourceName" />
</template>
<script setup name="MailMarketEdit" lang="ts">
// import * as CustomerApi from '@/api/customer/customer'
import UploadFile from '@/components/UploadFile/src/UploadFile.vue'
import type { UploadUserFile } from 'element-plus'

import * as MarketSettingApi from '@/api/market/marketSetting'
import * as MarketTemplateApi from '@/api/market/marketTemplate'
import * as MarketTaskApi from '@/api/market/marketTask'
import ReplyEdit from '../marketSetting/ReplyEdit.vue'
import SenderEdit from '../marketSetting/SenderEdit.vue'
import { Editor } from '@/components/Editor'
import RenameFile from '@/components/UploadFile/src/RenameFile.vue'
import { subjectMacro, contentMacro } from '@/views/market/marketMacro/macro'
import * as signatureApi from '@/api/mailbox/mailSignature'
import { MarketTaskStatusEnum, MailboxMailResourceTypeEnum } from '@/utils/constants'
const message = useMessage() // 消息弹窗

const subjectInputRef = ref()
const editorRef = ref()
const renameFileRef = ref()
const dialogTitle = ref('邮件营销')
const dialogVisible = ref(false)
const subjectMacroVisible = ref(false)
const contentMacroVisible = ref(false)
const signatureVisible = ref(false)
const isShowQueryCondition = ref(false)
const type = ref('create')

const fileList = ref<UploadUserFile[]>([])
const tableRef = ref()
const signatureList = ref()
const senderEditRef = ref()
const replyEditRef = ref()
const senderData = ref()
const replyData = ref()
const templateList = ref()
const templateId = ref()
const formRef = ref()
const receiversData = ref<any[]>([])
const selectCount = ref(0)
const taskData = ref({
  name: undefined,
  status: MarketTaskStatusEnum.DRAFT,
  senderId: undefined,
  replyId: undefined,
  subject: '',
  isScheduled: false,
  sendTime: undefined,
  content: { content: '' },
  resources: [] as any[],
  receivers: [] as any[]
})

const columns = [
  {
    type: 'selection',
    align: 'center'
  },
  {
    label: '邮件地址',
    prop: 'mailAddress'
  }
]

const formRules = reactive({
  name: [{ required: true, message: '请输入任务名称', trigger: 'change' }],
  senderId: [{ required: true, message: '请选择发件人', trigger: 'change' }]
})

/** 打开弹窗 */
const open = async (param) => {
  await initData()
  type.value = param.type

  if (param.type == 'create') {
    receiversData.value = param.mailAddresses
    if (senderData.value.length > 0) {
      taskData.value.senderId = senderData.value[0].id
      handleSenderAddressChange()
    }

    if (templateList.value.length > 0) {
      templateId.value = templateList.value[0].id
      handleTemplateChange()
    }
  } else {
    taskData.value = await MarketTaskApi.singleGet(param.id)
    receiversData.value = taskData.value.receivers
    if (taskData.value.resources.length > 0) {
      taskData.value.resources.forEach((resource) => {
        if (resource.resourceType == MailboxMailResourceTypeEnum.ATTACHMENT)
          fileList.value.push({
            name: resource.fileName,
            url: resource.urlName,
            size: resource.size
          })
      })
    }
  }

  dialogVisible.value = true
  setTimeout(() => {
    setTableSelect()
  }, 10)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const setTableSelect = () => {
  tableRef.value.getTableRef().toggleAllSelection()
  selectCount.value = receiversData.value.length
}

const initData = async () => {
  subjectMacroVisible.value = false
  contentMacroVisible.value = false
  signatureVisible.value = false
  taskData.value = {
    name: undefined,
    status: MarketTaskStatusEnum.DRAFT,
    senderId: undefined,
    replyId: undefined,
    subject: '',
    isScheduled: false,
    sendTime: undefined,
    content: { content: '' },
    resources: [],
    receivers: []
  }
  senderData.value = await MarketSettingApi.senderList({})
  replyData.value = await MarketSettingApi.replyList({})
  templateList.value = await MarketTemplateApi.simpleList()
  signatureList.value = await signatureApi.list()
  fileList.value = []
  receiversData.value = []
}

const handleTemplateChange = async () => {
  const templateContent = await MarketTemplateApi.getContentByTemplateId(templateId.value)
  taskData.value.content.content = templateContent.content
  templateList.value.forEach((template) => {
    if (template.id == templateId.value) taskData.value.subject = template.subject
  })
  const templateResources = await MarketTemplateApi.getResourceByTemplateId(templateId.value)
  fileList.value = []
  templateResources.forEach((resource) => {
    fileList.value.push({
      name: resource.fileName,
      url: resource.urlName,
      size: resource.size
    })
  })
}

const handleSubjectMacroClick = (index) => {
  const focusIndex = subjectInputRef.value.$el.children[0].selectionStart
  taskData.value.subject =
    taskData.value.subject.slice(0, focusIndex) +
    '%' +
    subjectMacro[index] +
    '%' +
    taskData.value.subject.slice(focusIndex)
  subjectMacroVisible.value = false
}

const handleSenderAddressChange = () => {
  senderData.value.forEach((data) => {
    if (data.id == taskData.value.senderId && data.replyId != null)
      taskData.value.replyId = data.replyId
  })
}

const replyEditSuccess = async () => {
  replyData.value = await MarketSettingApi.replyList({})
}

const senderEditSuccess = async () => {
  senderData.value = await MarketSettingApi.senderList({})
}

const handleSenderCreate = () => {
  senderEditRef.value.open('create', 0)
}

const handleReplyCreate = () => {
  replyEditRef.value.open('create', 0)
}

const handleDeleteResource = (item) => {
  fileList.value = fileList.value.filter((resourceItem) => {
    if (resourceItem == item) return false
    else return true
  })
}

const handleRenameResource = (item) => {
  const index = fileList.value.indexOf(item)
  renameFileRef.value.open(index, item.name)
}

const handleCopyResourceName = async (item) => {
  await navigator.clipboard.writeText(item.name)
}

const saveResourceName = (index, name) => {
  fileList.value[index].name = name
}

const handleContentMacroClick = (index) => {
  editorRef.value
    .getEditorRef()
    .getEditor()
    .insertContent('%' + contentMacro[index] + '%')
  contentMacroVisible.value = false
}

const handleSignatureClick = (index) => {
  editorRef.value.getEditorRef().getEditor().insertContent(signatureList.value[index].content)
  signatureVisible.value = false
}

const handleTableSelectChange = (newSelection) => {
  selectCount.value = newSelection.length
}

const emit = defineEmits(['success'])
/** 提交表单 */
const sendTask = async () => {
  taskData.value.status = MarketTaskStatusEnum.UNEXECUTED
  submitForm()
}

const submitForm = async () => {
  if (!formRef) return false
  await formRef.value.validate()

  taskData.value.receivers = []
  tableRef.value
    .getTableRef()
    .getSelectionRows()
    .forEach((row) => {
      taskData.value.receivers.push({ contactId: row.id, mailAddress: row.mailAddress })
    })

  taskData.value.resources = []
  fileList.value.forEach((file) => {
    taskData.value.resources.push({
      fileName: file.name,
      urlName: file.url,
      resourceType: MailboxMailResourceTypeEnum.ATTACHMENT,
      size: file.size
    })
  })
  if (taskData.value.receivers.length == 0) {
    message.error('请选择邮件地址')
    return
  }
  if (type.value == 'create') {
    await MarketTaskApi.create(taskData.value)
  } else {
    await MarketTaskApi.update(taskData.value)
  }
  if (taskData.value.status == MarketTaskStatusEnum.DRAFT) {
    message.success('保存成功')
  } else if (taskData.value.isScheduled) {
    message.success('定时发送成功')
  } else {
    message.success('发送成功')
  }
  dialogVisible.value = false
  emit('success')
}

const saveTask = () => {
  taskData.value.status = MarketTaskStatusEnum.DRAFT
  submitForm()
}
</script>
<style scoped>
.file-list {
  border: 0.5px solid #eaeaea;
  width: 200px;
  min-width: 200px;
  display: flex;
  flex-wrap: wrap;
  margin-right: 8px;
  margin-bottom: 5px;
}
.file-list > div {
  overflow: hidden;
  display: flex;
  flex-direction: column; /* 垂直排列 */
  align-items: left; /* 水平居中对齐 */
  justify-content: center; /* 垂直居中对齐 */
}

.file-list span {
  cursor: default;
  font-size: 10pt;
}
:deep(.el-upload-list) {
  display: none;
}
</style>
